/*
 * @Author: yangzonglong
 * @Date: 2021-05-17 10:56:52
 * @version: v1.0.0
 * @Descripttion: 通知节点基础设置
 * @LastEditors: 871387321@qq.com 871387321@qq.com
 * @LastEditTime: 2023-11-09 16:24:40
 * @Auditor: 
 */
import React, { useState, useContext, useCallback, useEffect, useMemo, useRef } from 'react';
import { Form, Input, Divider, Radio, RadioChangeEvent, Checkbox } from 'antd';
import context from '../context';
import Strategy from '../strategy/_Strategy';
import { createBpmnXMLNode, BPMN_NODE_TYPE } from './../../../utils/bpmnUtils';
import { ReceiveTaskProps, StartEventSelfProps, FormField } from './../../../interface';


const notifyStrategyDesc = '邮件通知';
export default () => {
  const isInit = useRef(false);
  const { self, modeler } = useContext(context);
  const [name, setName] = useState('');
  const [assignStrategy, setAssignStrategy] = useState('');
  const [users, setUsers] = useState<Array<{ id: string; name: string; }>>([]);
  const [vars, setVars] = useState<FormField[]>([]);
  const [errorHandlingCode, setErrorHandlingCode] = useState('10');
  const [notifyStrategy, setNotifyStrategy] = useState('10');

  const [ccStrategy, setCcStrategy] = useState('');
  const [ccStrategyUsers, setCcStrategyUsers] = useState<Array<{ id: string; name: string; }>>([]);

  const [bccStrategy, setBccStrategy] = useState('');
  const [bccStrategyUsers, setBccStrategyUsers] = useState<Array<{ id: string; name: string; }>>([]);

  const _self = self as ReceiveTaskProps;

  useEffect(() => {
    setName(_self.businessObject?.name || '');
    setAssignStrategy(_self.businessObject?.assignStrategy || '');
    setUsers(_self.businessObject?.extensionElements?.values?.[0]?.values || []);

    setErrorHandlingCode(_self.businessObject?.errorHandlingCode || '10');

    setNotifyStrategy(_self.businessObject?.notifyStrategy === '20' ? '20' : '10');

    setCcStrategy(_self.businessObject?.ccStrategy || '');
    setCcStrategyUsers(_self.businessObject?.extensionElements?.values?.[1]?.values || []);

    setBccStrategy(_self.businessObject?.bccStrategy || '');
    setBccStrategyUsers(_self.businessObject?.extensionElements?.values?.[2]?.values || []);
    setTimeout(() => isInit.current = true, 500);
    console.log(_self.businessObject);
  }, [_self]);

  useEffect(() => {
    const rootChildren = _self.parent?.children || [];
    const startEvent = rootChildren.find((item) => item.type === BPMN_NODE_TYPE.START_EVENT) as StartEventSelfProps;
    const globalVar: any = startEvent?.businessObject?.extensionElements?.values?.[0].values || [];

    setVars(globalVar);
  }, [_self]);

  const onChangeName = useCallback((e: React.BaseSyntheticEvent) => {
    setName(e.target.value);
    modeler.get('modeling').updateLabel(_self, e.target.value);
  }, [_self, modeler]);

  const onChangeErrorHandlingCode = useCallback((e: RadioChangeEvent) => {
    const v = e.target.value;
    setErrorHandlingCode(v);
    modeler.get('modeling').updateProperties(_self, {
      errorHandlingCode: v
    });
  }, [_self, modeler]);

  const onChangeStrategy = useCallback((data) => {
    if (!isInit.current) return;

    let assignValue = '';
    if (typeof data.assignValue === 'string') assignValue = data.assignValue;
    if (Array.isArray(data.assignValue)) assignValue = data.assignValue[0];

    modeler.get('modeling').updateProperties(_self, {
      assignStrategy: data.assignStrategy,
      assignValue: assignValue
    });

    if (data.assignValue) {
      const assignValue = Array.isArray(data.assignValue) ? data.assignValue : [data.assignValue];

      const ccValues = _self.businessObject!.extensionElements?.values?.[1];
      const bccValues = _self.businessObject!.extensionElements?.values?.[2];

      _self.businessObject!.extensionElements = Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.EXTENSION_ELEMENTS), {
        values: [
          Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.HL_USER_LIST), {
            values: assignValue.map((id: string, index: number) => {
              const name = data.assignDesc[index];
              return Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.HL_USER), { id, name });
            })
          }),
          ccValues || Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.HL_CC_USER_LIST), {
            values: []
          }),
          bccValues || Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.HL_BCC_USER_LIST), {
            values: []
          })
        ]
      });
    }

  }, [_self, modeler]);

  const onChangeCcStrategy = useCallback((data) => {
    if (!isInit.current) return;

    let assignValue = '';
    if (typeof data.assignValue === 'string') assignValue = data.assignValue;
    if (Array.isArray(data.assignValue)) assignValue = data.assignValue[0];

    modeler.get('modeling').updateProperties(_self, {
      ccStrategy: data.assignStrategy,
      ccValue: assignValue
    });

    if (data.assignValue) {
      const assignValue = Array.isArray(data.assignValue) ? data.assignValue : [data.assignValue];

      _self.businessObject!.extensionElements = Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.EXTENSION_ELEMENTS), {
        values: [
          _self.businessObject!.extensionElements?.values?.[0],
          Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.HL_CC_USER_LIST), {
            values: assignValue.map((id: string, index: number) => {
              const name = data.assignDesc[index];
              return Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.HL_USER), { id, name });
            })
          }),
          _self.businessObject!.extensionElements?.values?.[2],
        ]
      });
    }

  }, [_self, modeler]);

  const onChangeBccStrategy = useCallback((data) => {
    if (!isInit.current) return;

    let assignValue = '';
    if (typeof data.assignValue === 'string') assignValue = data.assignValue;
    if (Array.isArray(data.assignValue)) assignValue = data.assignValue[0];

    modeler.get('modeling').updateProperties(_self, {
      bccStrategy: data.assignStrategy,
      bccValue: assignValue
    });

    if (data.assignValue) {
      const assignValue = Array.isArray(data.assignValue) ? data.assignValue : [data.assignValue];

      _self.businessObject!.extensionElements = Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.EXTENSION_ELEMENTS), {
        values: [
          _self.businessObject!.extensionElements?.values?.[0],
          _self.businessObject!.extensionElements?.values?.[1],
          Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.HL_BCC_USER_LIST), {
            values: assignValue.map((id: string, index: number) => {
              const name = data.assignDesc[index];
              return Object.assign(createBpmnXMLNode(modeler, BPMN_NODE_TYPE.HL_USER), { id, name });
            })
          })
        ]
      });
    }

  }, [_self, modeler]);

  const defData = useMemo(() => ({
    assignStrategy,
    assignValue: users.map(item => item.id)
  }), [assignStrategy, users]);

  const ccStrategyData = useMemo(() => ({
    assignStrategy: ccStrategy,
    assignValue: ccStrategyUsers.map(item => item.id)
  }), [ccStrategy, ccStrategyUsers]);

  const bccStrategyData = useMemo(() => ({
    assignStrategy: bccStrategy,
    assignValue: bccStrategyUsers.map(item => item.id)
  }), [bccStrategy, bccStrategyUsers]);

  return (
    <Form layout='vertical'>
      <Form.Item label={window.$app.t('nodeId')} required>
        <Input disabled value={_self.businessObject?.id} />
      </Form.Item>
      <Form.Item label={window.$app.t('nodeName')} required>
        <Input value={name} onChange={onChangeName} />
      </Form.Item>
      <Strategy
        defData={defData}
        onChange={onChangeStrategy}
        vars={vars} />
      <Form.Item label={window.$app.t('errorHandling')} required>
        <Radio.Group value={errorHandlingCode} onChange={onChangeErrorHandlingCode}>
          <Radio value={'10'}>{window.$app.t('errorReport')}</Radio>
          <Radio value={'20'}>{window.$app.t('jump')}</Radio>
        </Radio.Group>
      </Form.Item>

      <Form.Item label={window.$app.t('notificationMethod')} required>
        <Checkbox onChange={e => {
          setNotifyStrategy(e.target.checked ? '10' : '20');
          modeler.get('modeling').updateProperties(_self, {
            notifyStrategy: e.target.checked ? '10' : '20',
            notifyStrategyDesc
          });
        }} checked={notifyStrategy === '10'}>{window.$app.t('notifyStrategy')}</Checkbox>
        <Checkbox disabled checked={true}>{window.$app.t('myUnderstand')}</Checkbox>
      </Form.Item>

      <Divider />
      {notifyStrategy === '10' && <>
        <Strategy
          label={window.$app.t('cc')}
          required={false}
          defData={ccStrategyData}
          onChange={onChangeCcStrategy}
          vars={vars} />
        <Divider />
        <Strategy
          label={window.$app.t('bcc')}
          required={false}
          defData={bccStrategyData}
          onChange={onChangeBccStrategy}
          vars={vars} />
      </>}
    </Form>
  );
};
